<template>
  <div class="login-boxs-item">
    <div class="switch-container">
      <span class="switch-container-solid" :class="{ 'switch-container-solid-active': type == 'password' }"></span>
      <p
        @click="switchType('phone')"
        class="switch-containe-item switch-containe-item-mg"
        :class="{ 'tip-active': type == 'phone' }"
      >
        手机号登录
      </p>
      <p @click="switchType('password')" class="switch-containe-item" :class="{ 'tip-active': type == 'password' }">
        账号登录
      </p>
      <!-- <div class="tip hw-click-cursor" @click="switchType('phone')" :class="{ 'tip-active': type == 'phone' }">
        <img class="tip-image" src="../../../assets/img/login.png" v-if="type == 'phone'" />
        <span>手机号登录</span> 
      </div>
      <div class="tip hw-click-cursor" @click="switchType('password')" :class="{ 'tip-active': type == 'password' }">
        <span>账号登录</span>
        <img class="tip-image2" src="../../../assets/img/login.png" v-if="type == 'password'" />
      </div> -->
    </div>

    <t-form
      ref="form"
      :class="['item-container', `login-${type}`]"
      :data="formData"
      :rules="FORM_RULES"
      label-width="0"
      @submit="onSubmit"
    >
      <!-- <span class="login-title" v-if="type == 'phone'">若您未注册,将使用输入的手机号自动注册</span> -->
      <template v-if="type == 'password'">
        <t-form-item name="account">
          <t-input v-model="formData.account" size="large" placeholder="请输入账号">
            <template #prefix-icon>
              <i class="doorIcon"> &#xe62d; </i>
            </template>
          </t-input>
        </t-form-item>

        <t-form-item name="password">
          <div class="password-box">
            <t-input
              v-model="formData.password"
              size="large"
              :type="showPsw ? 'text' : 'password'"
              :clearable="false"
              placeholder="请输入登录密码"
            >
              <template #prefix-icon>
                <i class="doorIcon"> &#xe631; </i>
              </template>
              <template #suffix>
                <t-popup
                  attach="#login-bt-401"
                  overlayClassName="popup"
                  class="placement top"
                  :content="!showPsw ? '显示密码' : '隐藏密码'"
                  placement="top"
                  showArrow
                  destroyOnClose
                >
                  <div>
                    <i v-if="!showPsw" class="doorIcon" @click="showPsw = !showPsw"> &#xe62a; </i>
                    <i v-else class="doorIcon" style="color: rgba(230, 43, 23, 1)" @click="showPsw = !showPsw">
                      &#xe630;
                    </i>
                  </div>
                </t-popup>
                <!-- <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" /> -->
              </template>
            </t-input>
          </div>
        </t-form-item>
      </template>

      <!-- 手机号登录 -->
      <template v-else>
        <t-form-item name="phone">
          <t-input :maxlength="11" v-model="formData.phone" size="large" placeholder="请输入手机号码">
            <template #prefix-icon>
              <i class="doorIcon"> &#xe632; </i>
            </template>
          </t-input>
        </t-form-item>

        <t-form-item class="verification-code" :class="{ 'verification-code-lock': codeLogin }" name="verifyCode">
          <t-input :maxlength="6" v-model="formData.verifyCode" size="large" placeholder="请输入验证码" />
          <t-button v-loading="codeLogin" variant="outline" :disabled="countDown > 0" @click="sendCode">
            {{ countDown == 0 ? '获取验证码' : `${countDown}秒后可重发` }}
          </t-button>
        </t-form-item>
      </template>

      <t-form-item v-if="type == 'phone'" class="btn-container" style="margin-bottom: 8px">
        <t-button
          block
          size="large"
          type="submit"
          :loading="loading"
          :disabled="!formData.phone || !formData.verifyCode"
        >
          {{ type === 'phone' ? '立即登录' : '登录' }}
        </t-button>
      </t-form-item>
      <t-form-item class="btn-container" v-else style="margin-bottom: 8px">
        <t-button
          block
          size="large"
          type="submit"
          :loading="loading"
          :disabled="!formData.account || !formData.password"
        >
          {{ type === 'phone' ? '立即登录' : '登录' }}
        </t-button>
      </t-form-item>
      <div class="check-container remember-pwd">
        <t-checkbox v-model="checkType"><span class="remember-pwd-title1">我已阅读并同意</span></t-checkbox>
        <span class="remember-pwd-title2" @click="pathagree(3)">《服务协议》</span>
        <span class="remember-pwd-title1">及</span>
        <span class="remember-pwd-title2" @click="pathagree(5)">《隐私协议》</span>
      </div>
      <t-divider>其他登录方式</t-divider>
      <div class="hw-flex-style-c-c">
        <t-icon @click="Setvisible" name="logo-wechat" size="30" style="color: RGBA(90, 194, 111, 1)"></t-icon>
      </div>
    </t-form>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck

import md5 from 'js-md5';
import { login, getUser, quick, portalCode } from '@/api/login/login';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next';
import { useCounter } from '@/hooks';
import { useUserStore } from '@/store';

const userStore = useUserStore();
const checkType = ref(true);
const loading = ref(false);
const codeLogin = ref(false);
const emit = defineEmits(['weixLogin']);
const INITIAL_DATA = {
  phone: '',
  account: '',
  password: '',
  verifyCode: '',
  checked: false,
};

const type = ref('phone');
const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);

const [countDown, handleCounter] = useCounter();
const phoneValidator = (val) => {
  let reg = /^1[1,2,3,4,5,6,7,8,9][0-9]{9}$/;

  if (reg.test(formData.value.phone) === false) {
    return { result: false, message: '请输入正确的手机号', type: 'error' };
  } else {
    return { result: true, type: 'success' };
  }
};
const FORM_RULES: Record<string, FormRule[]> = {
  phone: [{ required: true, message: '手机号必填', type: 'error' }, { validator: phoneValidator }],
  account: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  verifyCode: [{ required: true, message: '验证码必填', type: 'error' }],
};

const switchType = (val: string) => {
  type.value = val;
};
const Setvisible = () => {
  MessagePlugin.error('暂未开放');
  // emit('weixLogin');
};
const router = useRouter();
const route = useRoute();

/**
 * 发送验证码
 */

const sendCode = () => {
  if (codeLogin.value) {
    return;
  }
  form.value.validate({ fields: ['phone'] }).then((e) => {
    if (e === true) {
      codeLogin.value = true;
      portalCode({
        // templateKey: 'Default',
        type: 1,
        phone: formData.value.phone,
      }).then((res: any) => {
        if (res.statusCode == 200 && res.data) {
          handleCounter();
        } else {
          MessagePlugin.error(res.errors);
        }
        codeLogin.value = false;
      });
    }
  });
};
const pathagree = (e: number) => {
  router.push({
    path: '/portal/agree',
    query: {
      agreeType: e,
    },
  });
};
const onSubmit = async ({ validateResult }) => {
  if (!checkType.value) {
    MessagePlugin.error('请先同意记忆网用户协议');
    return;
  }
  if (validateResult === true) {
    loading.value = true;
    try {
      if (type.value == 'phone') {
        let typeCode = Number(formData.value.verifyCode);
        console.log(typeCode);
        if (isNaN(typeCode)) {
          MessagePlugin.error('请输入正确的验证码');
          loading.value = false;
          return;
        }

        let res: any = await quick({
          phone: formData.value.phone,
          HW_CE_SMSCode: formData.value.verifyCode,
        });
        if (res.statusCode == 200) {
          await userStore.getUserInfo();
          MessagePlugin.success('登录成功');
          const redirect = route.query.redirect as string;
          const redirectUrl = '/'; //redirect ? decodeURIComponent(redirect) : ;
          router.go(-1);
          // if (route.query.redirectType) {
          //   router.go(-1);
          //   return;
          // }
          // if (redirect) {
          //   window.location = route.query.redirect;
          // } else {
          //   router.push(redirectUrl);
          // }
        }
        loading.value = false;
        return;
      }
      // console.log(formData.value);
      let res: any = await login({ account: formData.value.account, password: md5(formData.value.password) });
      if (res.statusCode == 200) {
        await userStore.getUserInfo();
        MessagePlugin.success('登录成功');
        const redirect = route.query.redirect as string;
        const redirectUrl = '/'; //redirect ? decodeURIComponent(redirect) : ;
        router.go(-1);
        // if (route.query.redirectType) {
        //   router.go(-1);
        //   return;
        // }
        // if (redirect) {
        //   window.location = route.query.redirect;
        // } else {
        //   router.push(redirectUrl);
        // }
      } else {
        MessagePlugin.error(res.errors);
      }
      loading.value = false;
    } catch (e) {
      // console.log(e);
      loading.value = false;
      // MessagePlugin.error(e.message);
    }
  }
};
</script>

<style lang="less" scoped>
@import url('../index.less');

.login-boxs-item {
  width: 100%;
  display: flex;
  flex-direction: column;
  :deep(.t-checkbox.t-is-checked .t-checkbox__input) {
    border-color: #e62b17;
    background-color: #e62b17;
  }
  :deep(.t-form__item) {
    margin-bottom: 24px;
  }
}
.login-title {
  color: #999;
  font-family: PingFangSC-Regular, PingFang SC;
  margin-bottom: 8px;
}
:deep(.t-checkbox__input:hover) {
  border-color: #e62b17;
}
:deep(.t-button--variant-base.t-button--theme-primary.t-is-loading) {
  // background: rgba(210, 173, 119, 0.3);
  opacity: 0.5;
}
:deep(.t-button--variant-base.t-button--theme-primary.t-is-loading) {
  border-color: #e62b17;
}
.doorIcon {
  font-size: 24px;
  color: #9e9e9e;
}
.password-box {
  width: 100%;
  :deep(.t-input .t-input__suffix > .t-icon) {
    display: none;
  }
  .doorIcon {
    cursor: pointer;
    font-size: 24px;
    color: #9e9e9e;
  }
  :deep(.t-input .t-input__suffix:not(:empty)) {
    margin: 0;
  }
}

.register-bottoms {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-top: 24px;
  span {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.38);
    line-height: 22px;
  }
  .path-register {
    cursor: pointer;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #e62b17;
  }
}
.login-phone {
  padding-bottom: 8px !important;
}
.switch-container {
  position: relative;
  background: transparent;
  height: 34px;
}
.switch-container:hover {
  background: transparent;
}
.switch-container-solid {
  position: absolute;
  bottom: 0;
  left: 27px;
  transition: all 0.3s;
  width: 36px;
  height: 2px;
  background: #e62b17;
  border-radius: 2px;
}
.switch-containe-item {
  cursor: pointer;
  color: rgba(0, 0, 0, 0.8);
  text-align: center;
  font-family: 'PingFang SC';
  font-size: 18px;
  font-weight: 400;
  line-height: 28px; /* 155.556% */
}
.tip-active {
  color: rgba(230, 43, 23, 1);
}
.switch-container-solid-active {
  left: 140px;
}
.switch-containe-item-mg {
  margin-right: 32px;
}
.item-container {
  padding: 28px 0px;
  padding-right: 24px;
}
.btn-container {
  margin-top: 32px !important;
}
:deep(.t-button--variant-base.t-button--theme-primary.t-is-disabled) {
  background: #e62b17;
  border-color: #e62b17;
}
:deep(.t-divider__inner-text) {
  color: rgba(0, 0, 0, 0.38);
}
:deep(.t-divider) {
  margin-top: 48px;
  margin-bottom: 20px;
}
</style>
